package com.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.api.annotation.AuthToken;
import com.api.pojo.User;
import com.api.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @packageName: com.api.interceptor
 * @name: AuthorizationInterceptor
 * @description:
 * @author: 董定卓
 * @dateTime: 2019/6/26 14:15
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 如果打上了AuthToken注解则需要验证token
        if (method.getAnnotation(AuthToken.class) != null || handlerMethod.getBeanType().getAnnotation(AuthToken.class) != null) {
            String token = request.getParameter("token");
            logger.info("token is {}", token);
            if (token != null && token.length() != 0) {
                String userStr = RedisUtil.getString(token);
                logger.info("user is {}", userStr);
                if (userStr != null && userStr.length() != 0) {
                    String requestURI = request.getRequestURI();
                    User user = JSON.parseObject(userStr, User.class);
                    List<String> permissionUrls = user.getPermissionUrls();
                    if (!permissionUrls.contains(requestURI)) {
                        logger.error("访问[" + requestURI + "]权限不足");
                        response.setCharacterEncoding("utf-8");
                        response.setHeader("Content-type", "application/json;charset=UTF-8");
                        PrintWriter out = response.getWriter();
                        out.print("{\"code\":403,\"msg\":\"访问[" + requestURI + "]权限不足\"}");
                        out.flush();
                        out.close();
                        return false;
                    }
                    RedisUtil.expire(token, 1, TimeUnit.HOURS);
                } else {
                    logger.info("登录信息失效,请重新登录");
                    response.setCharacterEncoding("utf-8");
                    PrintWriter out = response.getWriter();
                    response.setHeader("Content-type", "application/json;charset=UTF-8");
                    out.print("{\"code\":401,\"msg\":\"登录信息失效,请重新登录\"}");
                    out.flush();
                    out.close();
                    return false;
                }
            } else {
                logger.info("token参数不存在");
                response.setCharacterEncoding("utf-8");
                PrintWriter out = response.getWriter();
                response.setHeader("Content-type", "application/json;charset=UTF-8");
                out.print("{\"code\":555,\"msg\":\"token参数不存在\"}");
                out.flush();
                out.close();
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }


}
